import openpyxl as xl
from openpyxl.worksheet.worksheet import Worksheet
from openpyxl.cell import MergedCell


def parser_merged_cell(sheet: Worksheet, row, col):
    """
    检查是否为合并单元格并获取对应行列单元格的值。
    如果是合并单元格，则取合并区域左上角单元格的值作为当前单元格的值,否则直接返回该单元格的值
    :param sheet: 当前工作表对象
    :param row: 需要获取的单元格所在行
    :param col: 需要获取的单元格所在列
    :return: 
    """
    cell = sheet.cell(row=row, column=col)
    if isinstance(cell, MergedCell):  # 判断该单元格是否为合并单元格
        for merged_range in sheet.merged_cell_ranges:  # 循环查找该单元格所属的合并区域
            # 判断是纵向的单元格
            if merged_range.size["columns"] == 1:
                _str = merged_range.coord.replace("A","E")
                # 获取值并相加
                ws = sheet[_str]
                for row in ws:
                    for cell in row:
                        print(cell.value)


if __name__ == "__main__":
    wb = xl.load_workbook(r"F:\my_profile\study\code_pub\study_code_pub\python表格\test1.xlsx")
    sheet_ = wb.active

    for row_index in range(1, 2):
        for col_index in range(1, 40):
            cell_ = parser_merged_cell(sheet_, row_index, col_index)
            # print(f"第{row_index}行第{col_index}列{cell_.value}")